package api

import (
	"gitee.com/zhaokangming/tiny-ticktok/model"
	"gitee.com/zhaokangming/tiny-ticktok/pkg/app"
	"gitee.com/zhaokangming/tiny-ticktok/pkg/errcode"
	"gitee.com/zhaokangming/tiny-ticktok/pkg/util/auth"
	"gitee.com/zhaokangming/tiny-ticktok/pkg/util/convert"
	"gitee.com/zhaokangming/tiny-ticktok/service"

	"github.com/gin-gonic/gin"
)

type UserResponse struct {
	app.Response
	User model.User `json:"user"`
}

// Register register account
func Register(c *gin.Context) {
	name := c.Query("username")
	password := c.Query("password")

	data, err := service.Register(c, name, password)
	if err != nil {
		app.WriteResponse(c, err, nil)
		return
	} else {
		app.WriteResponse(c, nil, data)
	}
}

// Login login and get a token
func Login(c *gin.Context) {
	name := c.Query("username")
	password := c.Query("password")

	data, err := service.Login(c, name, password)
	if err != nil {
		app.WriteResponse(c, err, nil)
		return
	} else {
		app.WriteResponse(c, nil, data)
	}

}

func UserInfo(c *gin.Context) {
	claims, ok := c.Value("claims").(*auth.Claims)
	if !ok {
		app.WriteResponse(c, errcode.ErrAuthCheckToken, nil)
		return
	}

	userID, ok := c.GetQuery("user_id")
	if !ok {
		app.WriteResponse(c, errcode.ErrParamTypeError, nil)
		return
	}

	var targetID int64
	if userID == "0" {
		targetID = claims.ID
	} else {
		targetID = convert.StrTo(userID).MustInt64()
	}

	user, err := service.QueryUser(c, claims.ID, targetID)
	if err != nil {
		app.WriteResponse(c, err, nil)
		return
	}

	app.WriteResponse(c, nil, &UserResponse{User: *user})
}
